package com.microservice.skeleton.gateway.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.microservice.skeleton.common.vo.Result;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: lijin
 * @date: 2018年09月26日
 */
public class OAuth2AuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {

        response.setContentType("application/json;charset=UTF-8;");
        PrintWriter writer = response.getWriter();

        String msg = "认证失败";
        if(authException instanceof InsufficientAuthenticationException){
            msg = "未登录";
        }else if(authException instanceof BadCredentialsException ||authException instanceof UsernameNotFoundException){
            msg = "用户名或者密码错误";
        }

        writer.println(new ObjectMapper().writeValueAsString(Result.failure(500, msg)));
        response.flushBuffer();

    }
}
